import React, { useState } from 'react';
import { Form, Typography, Message } from '@arco-design/web-react';
import { 
  IconPhone, 
  IconSafe, 
  IconWechat, 
  IconGithub,
  IconLock 
} from '@arco-design/web-react/icon';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import './Login.css';

// 导入API服务和类型定义
import { 
  sendSmsCode, 
  smsLogin, 
  setPassword,
  validatePhone,
  validateSmsCode,
  ApiError
} from '../../services/auth';
import { 
  SmsType, 
  SmsLoginFormData, 
  SetPasswordFormData 
} from '../../types/auth';

// 导入 seeker 卡通形象
import seeker1 from '../../assets/seeker/seeker1.png';
import seeker2 from '../../assets/seeker/seeker2.png';
import seeker3 from '../../assets/seeker/seeker3.png';
import seeker4 from '../../assets/seeker/seeker4.png';
import seeker5 from '../../assets/seeker/seeker5.png';

// 随机选择一个seeker图片
const seekerImages = [seeker1, seeker2, seeker3, seeker4, seeker5];
const randomSeekerImage = seekerImages[Math.floor(Math.random() * seekerImages.length)];

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [smsForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [showPasswordForm, setShowPasswordForm] = useState(false);
  const [phoneValue, setPhoneValue] = useState('');
  const [smsCodeValue, setSmsCodeValue] = useState('');
  const [passwordValue, setPasswordValue] = useState('');
  const [confirmPasswordValue, setConfirmPasswordValue] = useState('');
  
  /**
   * 错误状态管理
   * 用于存储和显示各种表单验证错误信息
   */
  const [passwordError, setPasswordError] = useState<string>('');
  const [confirmPasswordError, setConfirmPasswordError] = useState<string>('');
  const [formError, setFormError] = useState<string>('');
  
  const { t } = useTranslation();
  const navigate = useNavigate();

  // 短信登录表单提交
  const onSmsFinish = async (values: SmsLoginFormData) => {
    setLoading(true);
    console.log('短信登录表单数据:', values);
    
    try {
      // 验证手机号格式
      if (!validatePhone(phoneValue)) {
        Message.error(t('login.invalidPhone'));
        return;
      }

      // 验证验证码格式
      if (!validateSmsCode(smsCodeValue)) {
        Message.error(t('login.invalidSmsCode'));
        return;
      }

      // 调用短信登录API
      const response = await smsLogin({
        phone: phoneValue,
        smsCode: smsCodeValue
      });

      if (response.success) {
        Message.success(t('login.loginSuccess'));
        
        // 检查是否需要设置密码
        if (response.data.needSetPassword) {
          setShowPasswordForm(true);
        } else {
          // 直接跳转到主页
          navigate('/dashboard');
        }
      } else {
        Message.error(response.message || t('login.loginFailed'));
      }
    } catch (error) {
      console.error('短信登录失败:', error);
      if (error instanceof ApiError) {
        Message.error(error.message);
      } else {
        Message.error(t('login.loginFailed'));
      }
    } finally {
      setLoading(false);
    }
  };

  // 设置密码表单提交
  /**
   * 设置密码表单提交处理函数
   * 处理用户设置密码的表单提交，包括密码验证、API调用和页面跳转
   * 
   * @param values 设置密码表单数据，包含password和confirmPassword字段
   * @returns Promise<void> 异步处理结果
   * @throws ApiError 当API调用失败时抛出
   */
  const onPasswordFinish = async (values: SetPasswordFormData) => {
    console.log('开始处理设置密码请求:', {
      hasPassword: !!values.password,
      hasConfirmPassword: !!values.confirmPassword,
      timestamp: new Date().toISOString()
    });
    
    try {
      // 设置加载状态
      setLoading(true);
      
      // 清除之前的错误信息
      setFormError('');

      // 验证密码格式
      const passwordValidationError = validatePasswordFormat(passwordValue);
      if (passwordValidationError) {
        setPasswordError(passwordValidationError);
        setFormError('请检查密码格式要求');
        console.warn('密码格式验证失败:', { password: passwordValue });
        return;
      }

      // 验证两次密码是否一致
      const confirmPasswordValidationError = validatePasswordConfirm(passwordValue, confirmPasswordValue);
      if (confirmPasswordValidationError) {
        setConfirmPasswordError(confirmPasswordValidationError);
        setFormError('请确保两次输入的密码一致');
        console.warn('密码确认不一致');
        return;
      }

      console.log('密码验证通过，开始调用设置密码API');

      // 调用设置密码API
      const response = await setPassword({
        password: passwordValue,
        confirmPassword: confirmPasswordValue
      });

      console.log('设置密码API响应:', {
        success: response.success,
        code: response.code,
        message: response.message,
        timestamp: new Date().toISOString()
      });

      if (response.success) {
        console.log('密码设置成功，准备跳转到仪表板');
        Message.success(t('login.setPasswordSuccess'));
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          navigate('/dashboard');
        }, 1000);
      } else {
        const errorMsg = response.message || t('login.setPasswordFailed');
        console.error('设置密码失败:', {
          code: response.code,
          message: response.message,
          data: response.data
        });
        setFormError(errorMsg);
      }
    } catch (error) {
      console.error('设置密码过程中发生异常:', {
        error: error,
        errorMessage: error instanceof Error ? error.message : '未知错误',
        errorStack: error instanceof Error ? error.stack : undefined,
        timestamp: new Date().toISOString()
      });

      // 处理不同类型的错误
      if (error instanceof ApiError) {
        console.error('API错误详情:', {
          code: error.code,
          message: error.message,
          details: error.details
        });
        
        // 根据错误码提供更具体的错误信息
        let errorMessage = error.message;
        if (error.code === 401) {
          errorMessage = '登录状态已过期，请重新登录';
        } else if (error.code === 403) {
          errorMessage = '没有权限执行此操作';
        } else if (error.code === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        }
        
        setFormError(errorMessage);
      } else if (error instanceof Error) {
        // 处理网络错误或其他JavaScript错误
        if (error.message.includes('fetch')) {
          setFormError('网络连接失败，请检查网络连接');
        } else if (error.message.includes('timeout')) {
          setFormError('请求超时，请稍后重试');
        } else {
          setFormError(error.message || t('login.setPasswordFailed'));
        }
      } else {
        // 处理未知错误
        console.error('未知类型的错误:', error);
        setFormError(t('login.setPasswordFailed'));
      }
    } finally {
      // 无论成功还是失败都要清除加载状态
      setLoading(false);
      console.log('设置密码处理完成，清除加载状态');
    }
  };

  /**
   * 验证密码格式
   * 检查密码是否符合格式要求：至少8位，包含字母和数字
   * 
   * @param password 待验证的密码
   * @returns 错误信息，如果验证通过则返回空字符串
   */
  const validatePasswordFormat = (password: string): string => {
    if (!password) {
      return '密码不能为空';
    }
    
    if (password.length < 8) {
      return '密码长度至少8位';
    }
    
    if (!/[A-Za-z]/.test(password)) {
      return '密码必须包含字母';
    }
    
    if (!/\d/.test(password)) {
      return '密码必须包含数字';
    }
    
    if (password.length > 20) {
      return '密码长度不能超过20位';
    }
    
    return '';
  };

  /**
   * 验证确认密码
   * 检查确认密码是否与原密码一致
   * 
   * @param password 原密码
   * @param confirmPassword 确认密码
   * @returns 错误信息，如果验证通过则返回空字符串
   */
  const validatePasswordConfirm = (password: string, confirmPassword: string): string => {
    if (!confirmPassword) {
      return '请确认密码';
    }
    
    if (password !== confirmPassword) {
      return '两次输入的密码不一致';
    }
    
    return '';
  };

  /**
   * 处理密码输入变化
   * 实时验证密码格式并更新错误状态
   * 
   * @param value 输入的密码值
   */
  const handlePasswordChange = (value: string) => {
    setPasswordValue(value);
    
    // 实时验证密码格式
    const error = validatePasswordFormat(value);
    setPasswordError(error);
    
    // 如果确认密码已输入，重新验证确认密码
    if (confirmPasswordValue) {
      const confirmError = validatePasswordConfirm(value, confirmPasswordValue);
      setConfirmPasswordError(confirmError);
    }
    
    // 清除表单错误
    if (formError) {
      setFormError('');
    }
  };

  /**
   * 处理确认密码输入变化
   * 实时验证确认密码是否与原密码一致
   * 
   * @param value 输入的确认密码值
   */
  const handleConfirmPasswordChange = (value: string) => {
    setConfirmPasswordValue(value);
    
    // 实时验证确认密码
    const error = validatePasswordConfirm(passwordValue, value);
    setConfirmPasswordError(error);
    
    // 清除表单错误
    if (formError) {
      setFormError('');
    }
  };

  // 跳过设置密码
  const handleSkipPassword = () => {
    Message.info(t('login.skipPassword'));
    navigate('/dashboard');
  };

  // 发送短信验证码
  const sendVerificationCode = async () => {
    // 验证手机号格式
    if (!validatePhone(phoneValue)) {
      Message.error(t('login.invalidPhone'));
      return;
    }
    
    try {
      // 调用发送短信验证码API
      const response = await sendSmsCode({
        phone: phoneValue,
        type: SmsType.LOGIN
      });

      if (response.success) {
        Message.success(t('login.codeSent'));
        
        // 设置倒计时 (使用国际化配置的倒计时时间)
        const countdownTime = parseInt(t('login.countdownTime')) || 60;
        setCountdown(countdownTime);
        const timer = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        Message.error(response.message || t('login.sendCodeFailed'));
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      if (error instanceof ApiError) {
        Message.error(error.message);
      } else {
        Message.error(t('login.sendCodeFailed'));
      }
    }
  };

  // 微信登录
  const handleWechatLogin = () => {
    Message.info(t('login.wechatLoginComingSoon'));
    // 这里可以集成微信登录SDK
  };

  // GitHub登录
  const handleGithubLogin = () => {
    Message.info(t('login.githubLoginComingSoon'));
    // 这里可以集成GitHub登录SDK
  };

  // 渲染短信登录表单
  const renderSmsForm = () => (
    <Form
      form={smsForm}
      layout="vertical"
      onSubmit={onSmsFinish}
      autoComplete="off"
    >
      <div className="custom-input-wrapper">
        <div className="custom-input-icon">
          <IconPhone />
        </div>
        <input
          type="text"
          className="custom-input"
          placeholder={t('login.phonePlaceholder')}
          maxLength={11}
          value={phoneValue}
          onChange={(e) => setPhoneValue(e.target.value)}
        />
      </div>
      
      <div className="sms-code-wrapper">
        <div className="sms-code-input-wrapper">
          <div className="sms-code-input-icon">
            <IconSafe />
          </div>
          <input
            type="text"
            className="sms-code-input"
            placeholder={t('login.smsCodePlaceholder')}
            maxLength={6}
            value={smsCodeValue}
            onChange={(e) => setSmsCodeValue(e.target.value)}
          />
        </div>
        <button
          type="button"
          className={`custom-button sms-code ${countdown > 0 ? 'disabled' : ''}`}
          onClick={sendVerificationCode}
          disabled={countdown > 0}
        >
          {countdown > 0 ? `${countdown}s` : t('login.getSmsCode')}
        </button>
      </div>
      
      <button
        type="submit"
        className="custom-button primary"
        disabled={loading}
      >
        {t('login.signIn')}
      </button>
    </Form>
  );

  // 渲染设置密码表单
  /**
   * 渲染设置密码表单
   * 显示密码设置界面，包含密码输入框、确认密码输入框和相关按钮
   * 
   * @returns JSX.Element 设置密码表单组件
   */
  const renderPasswordForm = () => (
    <div className="password-form">
      <Text className="password-tip">{t('login.setPasswordTip')}</Text>
      
      {/* 显示表单级别的错误信息 */}
      {formError && (
        <div className="form-error">
          {formError}
        </div>
      )}
      
      <Form
        form={passwordForm}
        layout="vertical"
        onSubmit={onPasswordFinish}
        autoComplete="off"
      >
        <div className="custom-input-wrapper">
          <div className="custom-input-icon">
            <IconLock />
          </div>
          <input
            type="password"
            className={`custom-input ${passwordError ? 'error' : ''}`}
            placeholder={t('login.passwordPlaceholder')}
            value={passwordValue}
            onChange={(e) => handlePasswordChange(e.target.value)}
          />
        </div>
        
        {/* 显示密码错误信息 */}
        {passwordError && (
          <div className="input-error">
            {passwordError}
          </div>
        )}
        
        <div className="custom-input-wrapper">
          <div className="custom-input-icon">
            <IconLock />
          </div>
          <input
            type="password"
            className={`custom-input ${confirmPasswordError ? 'error' : ''}`}
            placeholder={t('login.confirmPasswordPlaceholder')}
            value={confirmPasswordValue}
            onChange={(e) => handleConfirmPasswordChange(e.target.value)}
          />
        </div>
        
        {/* 显示确认密码错误信息 */}
        {confirmPasswordError && (
          <div className="input-error">
            {confirmPasswordError}
          </div>
        )}
        
        <button
          type="submit"
          className="custom-button primary"
          disabled={loading || !!passwordError || !!confirmPasswordError}
        >
          {loading ? '设置中...' : t('login.setPassword')}
        </button>
        
        <button
          type="button"
          className="custom-button secondary"
          onClick={handleSkipPassword}
          disabled={loading}
        >
          {t('login.skipPassword')}
        </button>
      </Form>
    </div>
  );

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-illustration">
          <img src={randomSeekerImage} alt="Bug Seeker" className="seeker-image" />
          <Title heading={2} className="illustration-title">
            {t('login.welcome')}
          </Title>
          <Text className="illustration-subtitle">
            {t('login.subtitle')}
          </Text>
        </div>
        
        <div className="login-form-section">
          <div className="login-header">
            <Title heading={3}>
              {t('login.title')}
            </Title>
            <Text>{t('login.subtitle')}</Text>
          </div>
          
          {/* 根据状态显示短信登录表单或设置密码表单 */}
          <div className="login-form-container">
            <div className="form-wrapper">
              {showPasswordForm ? renderPasswordForm() : renderSmsForm()}
            </div>
          </div>
        
          {!showPasswordForm && (
            <div className="social-login">
              <Text className="social-login-text">{t('login.socialLogin')}</Text>
              <div className="social-icons">
                <button 
                  className="social-icon-button" 
                  onClick={handleWechatLogin}
                >
                  <IconWechat />
                </button>
                <button 
                  className="social-icon-button" 
                  onClick={handleGithubLogin}
                >
                  <IconGithub />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Login;